//% color="#1E90FF" iconWidth=50 iconHeight=40
namespace MoonshotAI {

    //% block="初始化kimi API密钥:[API] 模型:[MODEL] 温度:[TEMPERATURE]" blockType="command"
    //% API.shadow="string" API.defl="YOUR_API"
    //% MODEL.shadow="dropdown" MODEL.options="MODEL"
    //% TEMPERATURE.shadow="range" TEMPERATURE.params.max=100 TEMPERATURE.params.min=1 TEMPERATURE.defl="30"
   

    export function initializeMoonshotAI(parameter: any, block: any) {
	let kimi_api = parameter.API.code;
	let model = parameter.MODEL.code;
	let temperature = parameter.TEMPERATURE.code/100;
	Generator.addInclude('HTTPClient', '#include <HTTPClient.h>');
	Generator.addInclude('ArduinoJson', '#include <ArduinoJson.h>');
	Generator.addObject(`HTTPClient`, `HTTPClient`, `http;`);
	Generator.addObject(`DynamicJsonBuffer`, `DynamicJsonBuffer`, `jsonBuffer;`);
	Generator.addSetup(`begin`, `http.begin("https://api.moonshot.cn/v1/chat/completions");`);
	Generator.addSetup(`Content-Type`, `http.addHeader("Content-Type", "application/json");`);
	Generator.addSetup(`Authorization`, `http.addHeader("Authorization", ${kimi_api});`);
	Generator.addObject(`model`, `String`,`model="${model}";`);
	Generator.addObject(`temperature`, `float`,`temperature=${temperature};`);
	Generator.addObject(`chatmessages`, `String`,`chatmessages[10];`);
	Generator.addObject(`messageCount`, `int`,`messageCount = 1;`);
	Generator.addObject(`maxMessages`, `int`,`maxMessages = 10;`);
	
 }
    //% block="初始化kimi模型角色:[kimi_system] " blockType="command"
    //% kimi_system.shadow="string" kimi_system.defl="你是Kimi，你更擅长中文对话。你会为用户提供安全，有帮助，准确的回答。在回答中不要出现换行、回车等转意字符。"
    
    export function initializeMoonshotAISystem(parameter: any, block: any) {
	let kimi_system = parameter.kimi_system.code;
	
	Generator.addSetup(`chatmessages[0]`, `chatmessages[0] = R"({"role":"system","content":${kimi_system}})";`);
 }
 //% block="发送消息 [MESSAGE]轮数:[maxMessages]字数:[chatsize]" blockType="command"
 //% MESSAGE.shadow="string" MESSAGE.defl="你好，AI"
 //% maxMessages.shadow="range"   maxMessages.params.min=1    maxMessages.params.max=10    maxMessages.defl=5
//% chatsize.shadow="range"   chatsize.params.min=50    chatsize.params.max=200    chatsize.defl=150

    export function sendMessage(parameter: any, block: any) {
        let chatsize = parameter.chatsize.code;
	let userMessage = parameter.MESSAGE.code;
	let maxMessages = parameter.maxMessages.code;
       

	Generator.addCode(`	maxMessages=${maxMessages};`);

	Generator.addCode(`
		String mydata = String(R"({"model":")")+model+String(R"(","temperature":)")+String(temperature)+String(R"(,"messages":[)");
		for (int i = 0; i < messageCount; i++) {
			mydata += chatmessages[i];
			if (i < messageCount ) {
				mydata += ",";
			}
		}
		mydata += String(R"({"role":"user","content":" )") + ${userMessage} +String(R"(，字数为)")+${chatsize}+ String(R"(字"})");
	
		mydata += String("]}");
		http.POST(mydata);
		String jsonString=http.getString();
		JsonObject& root = jsonBuffer.parseObject(jsonString);
		String text = root["choices"][0]["message"]["content"];
		if (messageCount < maxMessages) {
			chatmessages[messageCount] = String(R"({"role":"user","content":" )") + ${userMessage} +String(R"(，字数为)")+${chatsize}+ String(R"(字"},)")+String(R"({"role":"assistant","content":" )") + text + String(R"("})");
			messageCount++;
		} else {
			for (int i = 0; i < maxMessages - 1; i++) {
				chatmessages[i] = chatmessages[i + 1];
			}
			chatmessages[maxMessages - 1] =  String(R"({"role":"user","content":" )") + ${userMessage} +String(R"(，字数为)")+${chatsize}+ String(R"(字"},)")+String(R"({"role":"assistant","content":" )") + text + String(R"("})");
		}
	`);

  }
   
    //% block="返回结果" blockType="reporter"
    export function reMessage(parameter: any, block: any) {
	Generator.addCode(`text`);
	}
 }
